<template>
  <cs-card>
    <el-table
      v-loading="isLoading"
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }"
      empty-text="没有数据"
      @selection-change="selectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="name" label="企业名称"> </el-table-column>
      <el-table-column prop="type" label="企业类型" width="100">
        <template v-slot="scoped">
          <span>{{ getEnterpriseType(scoped.row.type) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="overweightNum" label="超重次数" width="80"> </el-table-column>
      <el-table-column prop="address" label="详细地址">
        <template v-slot="scoped">
          {{ scoped.row.address ? scoped.row.address : '—' }}
        </template>
      </el-table-column>
      <el-table-column prop="longitude" label="经度" width="130">
        <template v-slot="scoped">
          {{ scoped.row.longitude ? scoped.row.longitude : '—' }}
        </template>
      </el-table-column>
      <el-table-column prop="latitude" label="纬度" width="130">
        <template v-slot="scoped">
          {{ scoped.row.latitude ? scoped.row.latitude : '—' }}
        </template>
      </el-table-column>
      <el-table-column prop="goodsType" label="企业源头货物类型" width="135">
        <template v-slot="scoped">
          <span>{{ getGoodsType(scoped.row.goodsType) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="corporate" label="企业法人" width="100">
        <template v-slot="scoped">
          {{ scoped.row.corporate ? scoped.row.corporate : '—' }}
        </template>
      </el-table-column>
      <el-table-column prop="corporatePhone" label="企业法人电话" width="120">
        <template v-slot="scoped">
          {{ scoped.row.corporatePhone ? scoped.row.corporatePhone : '—' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="120">
        <template v-slot="scoped">
          <el-link type="primary" @click="detailsBtnClick(scoped.row.id)">详情</el-link>
          <el-link
            v-if="innerMenu.upd.flag"
            type="primary"
            @click="alterBtnClick(scoped.row, currentPage)"
            >修改</el-link
          >
        </template>
      </el-table-column>
    </el-table>
    <div id="pagination_section">
      <span class="currentSelect">{{ `已选${currentSelect}项，共${totalCount}项` }}</span>
      <div class="pagination_right">
        <span>{{ `${pageSize}条/页` }}</span>
        <cs-pagination
          :currentPage="currentPage"
          :totalPage="totalPage"
          @firstPageClick="firstPageClick"
          @previousPageClick="previousPageClick"
          @nextPageClick="nextPageClick"
          @lastPageClick="lastPageClick"
          @junkToOtherPage="junkToOtherPage"
        />
      </div>
    </div>
  </cs-card>
</template>

<script>
import csCard from '@/components/cs-card/cs-card.vue'
import csPagination from '@/components/cs-pagination/cs-pagination.vue'
import {
  searchEnterprise,
  companyexportlist,
  getGoodsType
} from '@/service/source_manage/enterprise_manage.js'

export default {
  components: {
    csCard,
    csPagination
  },
  props: {
    innerMenu: {
      require: true,
      type: Object
    }
  },
  data() {
    return {
      tableData: [],
      checkListDefaultData: ['国有', '集体', '股份制', '私营', '其他'],
      goodsTypeArray: [],
      enterpriseName: '',
      // 当前页码
      currentPage: 1,
      // 一页的条数
      pageSize: 10,
      // 总共多少条数据
      totalCount: 0,
      // 总共多少页
      totalPage: 0,
      currentSelect: 0,
      tableOffset: 7,
      selectId: [],
      isLoading: true
    }
  },
  created() {
    // 发送当前选择的数量
    this.$bus.$emit('currentSelect_Enterprise', this.currentSelect)
    // 页码刚开始加载就查询所有企业信息
    this.searchEnterprise()
    // 当新增企业后，重新查询所有企业信息
    this.$bus.$on('addEnterpriseSuccess', () => {
      this.searchEnterprise(this.currentPage)
    })
    // 按名字搜索企业
    this.$bus.$on('searchentErpriseData', (res) => {
      if (this.isLoading) return
      this.enterpriseName = res
      this.searchEnterprise(this.currentPage, this.pageSize)
    })
    // 当修改企业成功后，重新查询所有企业信息
    this.$bus.$on('alterSourceSuccess', () => {
      this.searchEnterprise(this.currentPage)
    })
    // 删除企业成功后重新请求表格数据
    this.$bus.$on('delEnterpriseSuccess', () => {
      this.searchEnterprise(1, this.pageSize)
    })
    this.$bus.$on('exportlistcompany', (res) => {
      this.enterpriseName = res
      this.exportfn()
    })
    this.$bus.$on('dayBtnClick_7', () => {
      this.tableOffset = 7
      this.searchEnterprise()
    })
    this.$bus.$on('dayBtnClick_30', () => {
      this.tableOffset = 30
      this.searchEnterprise()
    })
    this.$bus.$on('addGoodsTypeSuccess', () => {
      this.getGoodsType_online()
    })
    this.getGoodsType_online()
  },
  beforeDestroy() {
    this.$bus.$off('exportlistcompany')
    this.$bus.$off('currentSelect_Enterprise')
    this.$bus.$off('detailsBtnCexportlistlick')
    this.$bus.$off('alterBtnClick')
    this.$bus.$off('emitEnterpriseDelID')
  },
  methods: {
    // 获取货物类型
    async getGoodsType_online() {
      const { code, data } = await getGoodsType()
      if (code === 0) {
        this.goodsTypeArray = data
      }
    },
    async exportfn() {
      const loading = this.$loading({
        lock: true,
        text: '下载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const data = await companyexportlist({ name: this.enterpriseName })
      if (!!data) {
        const filename = '企业信息表.xlsx'
        const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
          window.navigator.msSaveBlob(blob, decodeURI(filename))
        } else {
          // 创建新的URL并指向File对象或者Blob对象的地址
          const blobURL = window.URL.createObjectURL(blob)
          // 创建a标签，用于跳转至下载链接
          const tempLink = document.createElement('a')
          tempLink.style.display = 'none'
          tempLink.href = blobURL
          tempLink.setAttribute('download', decodeURI(filename))
          // 兼容：某些浏览器不支持HTML5的download属性
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          // 挂载a标签
          document.body.appendChild(tempLink)
          tempLink.click()
          document.body.removeChild(tempLink)
          // 释放blob URL地址
          window.URL.revokeObjectURL(blobURL)
        }
        setTimeout(() => {
          loading.close()
        }, 2000)
      } else {
        setTimeout(() => {
          loading.close()
        }, 2000)
      }
    },
    detailsBtnClick(id) {
      this.$bus.$emit('detailsBtnClick', id)
    },
    alterBtnClick(row) {
      this.$bus.$emit('alterBtnClick', row)
    },
    // 查询所有企业信息
    async searchEnterprise(
      pageNum = 1,
      pageSize = 10,
      name = this.enterpriseName,
      contactsName = '',
      offset = this.tableOffset
    ) {
      this.isLoading = true
      try {
        const { code, data } = await searchEnterprise(pageNum, pageSize, name, contactsName, offset)

        // console.log(data.data.data.list)
        if (code === 0) {
          this.tableData = []
          const tabelData = data
          console.log(tabelData.list)
          tabelData.list.forEach((item) => {
            this.tableData.push({
              id: item.id,
              name: item.name,
              type: item.type,
              overweightNum: item.overweightNum,
              address: item.address,
              longitude: item.longitude,
              latitude: item.latitude,
              goodsType: item.goodsType,
              corporate: item.corporate,
              corporatePhone: item.corporatePhone,
              personLiable: item.contactsName,
              personLiablePhone: item.contactsPhone,
              contactsIdCard: item.contactsIdCard,
              remarks: item.remark
            })
          })
          // 当前页码
          this.currentPage = tabelData.currPage - 0
          // 一页的条数
          this.pageSize = tabelData.pageSize
          this.totalCount = tabelData.totalCount
          this.totalPage = tabelData.totalPage - 0
          this.isLoading = false
        } else {
          this.$message.error('获取表格数据失败')
        }
      } catch (err) {
        console.log(err)
        this.$message.error('获取表格数据失败')
      }
    },
    // 获取企业类型
    getEnterpriseType(typeNum) {
      return this.checkListDefaultData[typeNum]
    },
    // 获取货物类型
    getGoodsType(type) {
      // if (type === 0) {
      //   return '散货'
      // } else if (type === 1) {
      //   return '集装箱'
      // } else if (type === 2) {
      //   return '高岭土'
      // } else if (type === 3) {
      //   return '沥青'
      // }
      if (type) {
        return this.goodsTypeArray[type]
      } else {
        return '—'
      }
    },
    // 第一页
    firstPageClick() {
      if (this.isLoading) return
      this.searchEnterprise(1)
    },
    // 上一页
    previousPageClick() {
      if (this.isLoading) return
      this.searchEnterprise(this.currentPage - 1)
    },
    // 下一页
    nextPageClick() {
      if (this.isLoading) return
      this.searchEnterprise(this.currentPage + 1)
    },
    // 最后一页
    lastPageClick() {
      if (this.isLoading) return
      this.searchEnterprise(this.totalPage)
    },
    // 跳转页
    junkToOtherPage(page) {
      this.searchEnterprise(page, this.pageSize)
    },
    // 表格选择项变化时触发事件
    selectionChange(selection) {
      this.selectId = []
      // 获取当前选择多少项
      this.currentSelect = selection.length
      this.$bus.$emit('currentSelect_Enterprise', this.currentSelect)
      selection.forEach((item) => {
        this.selectId.push(item.id)
      })
      this.$bus.$emit('emitEnterpriseDelID', this.selectId)
      console.log(this.selectId)
    }
  }
}
</script>

<style scoped>
/* 表格样式start */

.el-form-item >>> .el-form-item__label {
  color: #888888;
}

.el-select >>> .el-input__inner {
  border-radius: 0;
}

.el-input >>> .el-input__inner {
  border-radius: 0;
}

.el-textarea >>> .el-textarea__inner {
  border-radius: 0;
}

.form-select {
  width: 100%;
}

.el-link {
  display: inline-block;
  margin-right: 16px;
}

/* 表格选择框样式start */
.el-table >>> .el-checkbox__inner {
  width: 20px;
  height: 20px;
}

.el-table >>> .el-checkbox__inner::after {
  top: 3px;
  left: 6px;
}

.el-table >>> .el-checkbox__inner::before {
  top: 8px;
}
/* 表格选择框样式end */

/* 去掉switch外层的div溢出隐藏 */
.el-table >>> .cell {
  overflow: visible;
}

/* 设置switch的宽高边框 */
.el-switch >>> .el-switch__core {
  width: 28px !important;
  height: 14px;
  border: 2px solid #dddddd !important;
}

/* 设置switch圆形按钮的宽高边框位置 */
.el-switch >>> .el-switch__core:after {
  top: -4px;
  width: 14px;
  height: 14px;
  border: 2px solid #dddddd;
}

/* 设置switch圆形按钮的激活位置 */
.el-switch.is-checked >>> .el-switch__core::after {
  left: 106%;
}

/* 设置switch圆形按钮的关闭位置 */
.el-switch >>> .el-switch__core:after {
  left: -2px;
}

/* 表格样式end */
</style>
